using System;
using System.Collections.Generic;
using RomanJendrusz.Amazon.ETL.Messages;
using Castle.Core;
using System.Linq;

namespace RomanJendrusz.Amazon.ETL.Infrastructure.Bus
{
    public class AmazonBus: IBus
    {
        private readonly IRequestHandlerFactory requestHandlerFactory;
        private const int AllowedBatchedRequests = 2;

        public AmazonBus(IRequestHandlerFactory requestHandlerFactory)
        {
            this.requestHandlerFactory = requestHandlerFactory;
        }

        public AmazonResponse Process(AmazonRequest request)
        {
            if (request == null) throw new ArgumentNullException("request");
            var handler = requestHandlerFactory.GetRequestHandler(request);
            return handler.HandleRequest(request);
        }

        public AmazonResponse[] Process(AmazonRequest[] requests)
        {
            var responses = new List<AmazonResponse>();
            var groupedRequests = from req in requests
            group req by req.Destination
            into g select new {Destination = g.Key, Requests = g};
            foreach (var destRqsts in groupedRequests)
            {
                var handler = requestHandlerFactory.GetRequestHandler(destRqsts.Destination);
                for (int i = 0; i < destRqsts.Requests.Count(); )
                {
                    var partionatedRequests = destRqsts.Requests.Skip(i).Take(AllowedBatchedRequests).ToArray();
                    var handledResponses = handler.HandleRequest(partionatedRequests);
                    i += AllowedBatchedRequests;
                    responses.AddRange(handledResponses);
                }
            }
            return responses.ToArray();
        }
    }
}